var lstpId = new Array();
var lstpQty = new Array();
var count = 0;
var currency = 1;
var currencyType = 'SGD';
$(function(){
    $("#pageHeader").load("pageHeader.html"); //to include header in all pages
    $("#footer").load("footer.html");
    
    count =0;
    
    
    $("#currencyType").change(function(){
        //alert("on change event");
         currencyType = $('#currencyType option:selected').val();
               //alert('currtype si ' + currencyType);
         $.ajax({
         url: 'http://rate-exchange.appspot.com/currency?from=SGD&to='+currencyType,
         dataType: 'jsonp',
         success: function (data) {
            if(currencyType!=='SGD')
            {
                //alert( data.rate +',' +data.to)
                currency = data.rate;
                currencyType=data.to;
            }
            else
            {
                currency = 1;
                currencyType ="SGD";
            }

            $("#leftContent").text("");
            //$("#cart").text("");
            createItems();
         },
         error: function(){
             alert("cannot change now");
         }
        });


    });
    

});


function createItems()
{
       var promise = $.getJSON("getProductList");
       promise.done(function(data) {

           //to get how many item do we have
           //console.log(data.length)
           var c = 0;

           var numOfRow =parseInt(data.length/3);
           var numOfElement = data.length;

           if(numOfElement%3 != 0)
               numOfRow++;

           console.log("number of elements ---------> " + numOfElement);
           console.log("number of rows--------> " + numOfRow);

           for(var i=0;i<numOfRow;i++)
           {
               jQuery('<div/>',{
                        id:'row'+i,
                        class:'row'}).appendTo($("#leftContent"));
           }

           for(var j=0;j<numOfRow;j++)
           {
               for(var z=0;z<3;z++)
               {
                   jQuery('<div/>',{
                        id:'item'+c,
                        class:'col-lg-4 portfolio-item'}).appendTo($("#row"+j));
                    c++;
               }
           }
           for(var iThumb=0; iThumb < numOfElement; iThumb++)
           {
               jQuery('<div/>',{
                        id:'thumb'+iThumb,
                        class:'thumbnail'}).appendTo($("#item"+iThumb));
           }

           for(var iImg=0; iImg < numOfElement; iImg++)
           {
               jQuery('<img/>',{
                        class:'img-responsive',
                        src: 'images/' + data[iImg].pImg
                    }).appendTo($("#thumb"+iImg));

               jQuery('<div/>',{
                   id:'cap'+iImg,
                   class:'caption'
               }).appendTo($("#thumb"+iImg));

               jQuery('<h5/>',{
                   class:"pull-right",
                   id:"pPrice"+iImg
               }).text(currencyType + " " + (data[iImg].pPrice * currency).toFixed(2)).appendTo($("#cap"+iImg));

               jQuery('<h4/>',{
                   id:"pName"+iImg
               }).text(data[iImg].pName).appendTo($("#cap"+iImg));

               jQuery('<p/>',{
                   id:"pDesc"+iImg
               }).text(data[iImg].pDesc).appendTo($("#cap"+iImg));


               $('#cap'+iImg).append(
                       $('<p/>').append(
                       $('<button/>',{
                           id:'btnAdd'+data[iImg].pId,
                           class:'btn btn-primary',
                           onclick:'addToCart("' + data[iImg].pId + '","' +data[iImg].pName +
                                   '","' +data[iImg].pPrice +
                                   '","' +data[iImg].pQty +'")'
                          //onclick:'addToCart("strawberry")'
                       }).text("Add To Cart")).append(
                       $('<span/>',{
                           class:'badge pull-right',
                           id:"qtyleft"+data[iImg].pId
                       }).text(data[iImg].pQty + " left")));
                       
                if(data[iImg].pQty ==0)
                {
                   $("#btnAdd"+data[iImg].pId).attr("disabled","disabled");
                }

           }
           checkShoppingCart();
       }).fail(function(data) {
           console.log("fail ------");
       }).always(function(data) {
           console.log("-----> always");
       });

}

function checkShoppingCart()
{
    var promise = $.getJSON("checkShoppingCart");
    promise.done(function(data){
        //alert("data length -->" + data.length)
        if(data.length>0)
        {
            $("#currencyType").attr("disabled","disabled");
            //$("#BtnSgd").attr("disabled","disabled");
            for(var i=0; i < data.length; i++)
            {
                lstpId[count]=data[i].pId;
                lstpQty[count]=data[i].qtyInStore;
                count++;
                //console.log("count-->" + count);
                $('#cart').append(
                $('<tr/>',{ id:"tblRow"+data[i].pId}).append(
                $('<td/>').append(
                $('<button/>',{
                    class:'btn btn-default btn-danger btn-xs',
                    onclick:'removeOne(' + data[i].pId + ','+ data[i].qtyInStore +')'
                }).append(
                $('<span/>',{
                    class:'glyphicon glyphicon-remove-sign'
                   })))).append(
                $('<td/>').text(data[i].pName)).append(
                $('<td/>').text((data[i].pPrice * currency).toFixed(2))).append(
                $('<td/>').append(
                $('<input/>',{
                    type:'number',
                    id:'tempQty'+data[i].pId,
                    min:"1",
                    value:data[i].pQty,
                    max:data[i].qtyInStore,
                    class:'form-control',
                    onkeyup:"if(!this.checkValidity()){this.value='1';alert('Please enter a valid number between 1 to " +
                            data[i].qtyInStore + "');}",
                    onchange:"calcPrice(this.value,+"+ data[i].pId +"," + data[i].pPrice * currency+ ",'"+ 
                            data[i].pName +"',"+ data[i].qtyInStore + ")"

                }))).append(
                $('<td/>',{
                    id:'price'+data[i].pId
                }).text(data[i].pPrice * currency)).append(
                ).append('<hr/>'));
        
                //if(content <  )              
                //need to calculate the price, change the qty left, and add to the session cart
                calcPrice(data[i].pQty,data[i].pId,data[i].pPrice * currency,data[i].pName,data[i].qtyInStore);
                
                
            }
        }
        }).fail(function(data) {
           console.log("no data in the session------");
       }).always(function(data) {
           console.log("-----> always");
       });;
}


function addToCart(pId,pName,pPrice,pQty)
{
   //console.log("count -->" + count);
    //alert(pQty);
    $("#currencyType").attr("disabled","disabled");
    //$("#btnSgd").attr("disabled","disabled");
    for (i=0;i<lstpId.length;i++)
    {
        console.log("value in lstpid" + lstpId[i]);
        //to check if the item is already in the cart
        if(lstpId[i]== pId)
        {
            $("#tempQty"+pId).val(parseInt($("#tempQty"+pId).val())+1);
            //changeQtyLeft(pId,pQty,$("#tempQty"+pId).val());
            calcPrice($("#tempQty"+pId).val(),pId,pPrice*currency,pName,pQty);
            return;
        }

    }

            lstpId[count]=pId;
            lstpQty[count]=pQty;
            count++;
            //console.log("count-->" + count);
            var qty = 1;
            $('#cart').append(
            $('<tr/>',{ id:"tblRow"+pId}).append(
            $('<td/>').append(
            $('<button/>',{
                class:'btn btn-default btn-danger btn-xs',
                onclick:'removeOne(' + pId + ','+ pQty + ')'
            }).append(
            $('<span/>',{
                class:'glyphicon glyphicon-remove-sign'
               })))).append(
            $('<td/>').text(pName)).append(
            $('<td/>').text((pPrice*currency).toFixed(2))).append(
            $('<td/>').append(
            $('<input/>',{
                type:'number',
                id:'tempQty'+pId,
                min:"1",
                max:pQty,
                value:1,
                class:'form-control',
                onkeyup:"if(!this.checkValidity()){this.value='1';alert('Please enter a valid number between 1 to " +
                        pQty + "'); calcPrice(this.value,+"+ pId +"," + pPrice*currency+ ",'"+ pName +"',"+ pQty + ");}",
                onchange:"calcPrice(this.value,+"+ pId +"," + pPrice*currency+ ",'"+ pName +"',"+ pQty + ")"

            }))).append(
            $('<td/>',{
                id:'price'+pId
            }).text(pPrice)).append(
            ).append('<hr/>'));
            //alert($("#tempQty"+pId).val());

            calcPrice(qty,pId,pPrice*currency,pName,pQty);
            //changeQtyLeft(pId,pQty,$("#tempQty"+pId).val());
            
}




function changeQtyLeft(id,pQty,q)  //qQty=storeInQty, q = itemQuantity
{
    
    
     $("#qtyleft"+id).text(pQty - q  + " left");
     if(pQty-q ==0)
     {
        $("#btnAdd"+id).attr("disabled","disabled");
     }
     else
     {
         $("#btnAdd"+id).removeAttr("disabled");
     }
     
     
     
     
     
//    var temp = $("#qtyleft"+id).text();
//    var space = tempQty.indexOf(" ");
//    var tempQty = temp.substr(0,space);
//    
//     $.post("changeQuantity", {
//            "productId": id,
//            "productQty": q,
//            "qtyInStore":pQty,
//            "tempQty":tempQty
//        }).done(function(data) {
//            console.log("success");
//        }).fail(function(data) {
//            console.log("fail");
//        });
//
//
//    var event = new EventSource("invUpdate");
//    event.addEventListener("current", newQty);
    
     
 }
 
 

//function newQty(result)
//{
//    console.log("new Qty function");
//    //console.log(JSON.stringify(result));
//    var d = JSON.parse(result.data);
//    console.log(d.jId +' '+ d.jQtyInStore +' '+ d.jQty);
//    $("#qtyleft"+d.jId).text(d.jQtyInStore - d.jQty + " left");
//    console.log($("#qtyleft"+d.jId).text());
//}

function calcPrice(q,p,prz,name,pQty) //q = itemqty , pQty = total Qty
{
    $("#price"+p).text((q*prz).toFixed(2));
    if(q==null)
    {
        q=1;
    }
    //alert("in calcPrice " + p + "," +pQty + ","+ q);
    //changeQtyLeft(p,pQty,$("#tempQty"+p).val());
    //addToSessionCart(p,name,prz,q,pQty);
    
    changeQtyLeft(p,pQty,q);
    //$("#qtyleft"+id).text(qtyInStore - qty  + " left");
    var promise = $.post("shoppingCart",{ pId:p, pName:name, pPrice:prz, pQty:q, qtyleft:pQty});
    return;

}

function removeAll()
{
    $("#currencyType").removeAttr('disabled');
    //$("#btnSgd").removeAttr('disabled');
     $("[id^='tblRow']").remove();
     for(var i=0; i<lstpId.length; i++)
     {
         changeQtyLeft(lstpId[i],lstpQty[i],0);
     }
     var promise = $.post("removeCart");
     promise.done(function(){
         count=0;
         lstpId.length=0;
         lstpQty.length = 0;
         alert("already remove items in shopping cart");
     });
}

function removeOne(pId,pQty)
{
    $("[id='tblRow"+pId+"']").remove();
    changeQtyLeft(pId,pQty,0);
    
    for(var i=0; i<lstpId.length;i++)
    {
        console.log(lstpId[i]);
        if(lstpId[i]==pId)
        {
            lstpId.splice(i,1);
            lstpQty.splice(i,1);
            count--;
        }
    }

     if(lstpId.length==0)
     {             
         $("#currencyType").removeAttr("disabled");
     }
    var promise = $.post("removeCart",{pId:pId});
     promise.done(function(){

         alert("already remove one itme from shopping cart");
     }).fail(function() 
     {
         alert("fail");
     });

}

function checkOut()
{
    var promise = $.post("checkOut");
    promise.done(function(){
        //alert('done successfully');
        window.location.href="successOrder.html";

    });
    
    var promise1 = $.post("MailApp");
    promise.done(function(){
        alert('Invoice sent successfully');
       
        
    });
}
